package com.zhongli.devplatform.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongli.devplatform.bean.SecurityHelper;
import com.zhongli.devplatform.dto.sys.ChapterExercisesDTO;
import com.zhongli.devplatform.po.sys.*;
import com.zhongli.devplatform.po.view.ViewUserPO;
import com.zhongli.devplatform.service.imp.sys.ReadChapterExercisesService;
import com.zhongli.devplatform.service.imp.sys.ReadChapterExercisesTopicService;
import com.zhongli.devplatform.service.imp.sys.ReadKnowledgePointService;
import com.zhongli.devplatform.service.imp.sys.ReadTopicService;
import com.zhongli.devplatform.service.imp.view.ViewUserService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.utils.DateUtil;
import com.zhongli.devplatform.vo.TopicVO;
import com.zhongli.devplatform.vo.student.ChapterExercisesAndStudentVO;
import com.zhongli.devplatform.vo.sys.ChapterAndKnowledgeVO;
import com.zhongli.devplatform.vo.sys.ChapterExercisesVO;
import com.zhongli.devplatform.bean.Res;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wy
 * @since 2020/7/31
 */
@Api(tags = "题库", description = "题库，章节练习题")
@RestController
@RequestMapping("/topic")
public class TopicController {

    @Autowired
    private ReadTopicService readTopicService;

    @Autowired
    private ReadKnowledgePointService knowledgePointService;

    @Autowired
    private ViewUserService viewUserService;

    @Autowired
    private ReadChapterExercisesService chapterExercisesService;

    @Autowired
    private ReadChapterExercisesTopicService chapterExercisesTopicService;





    /**
     * 创建章节练习
     * @param id 知识点
     * @return 该知识点所有题目
     */
    @ApiOperation("根据当前学生所选知识点 获取视频信息")
    @GetMapping("/getKnowledge/{id}")
    public Res getKnowledge(@ApiParam(value = "知识点id",required = true) @PathVariable Integer id){
        ReadKnowledgePointPO data = knowledgePointService.getById(id);
        return Res.ok(data);
    }

    /**
     * 创建章节练习
     * @param id 知识点
     * @return 该知识点所有题目
     */
    @ApiOperation("根据当前学生所选知识点获取所有的练习题")
    @GetMapping("/getTopicByKnowledge/{id}")
    public Res getTopicByKnowledge(@ApiParam(value = "知识点id",required = true) @PathVariable Integer id){
        ChapterExercisesVO data = readTopicService.createChapterExercises(id);
        return Res.ok(data);
    }


    /**
     * 保存练习题
     * @param exercisesDTO {@link ChapterExercisesDTO} 接收前端
     * @return 返回章节练习信息
     */
    @ApiOperation("保存练习题")
    @PostMapping("/saveContactAnswers")
    public Res saveContactAnswers(@RequestBody ChapterExercisesDTO exercisesDTO){
        ReadChapterExercisesPO data =  chapterExercisesService.checkAnswer(exercisesDTO);
        Integer minutes = DateUtil.getBetweenMinutes(data.getStartTime(), data.getEndTime());
        data.setDuration(minutes);
        return Res.ok(data);
    }

    /**
     * 获取所有题目解析
     * @param exercisesId  练习id
     * @return 所有题目解析
     */
    @ApiOperation("获取当前章节练习id->所有题目解析")
    @GetMapping("/allTopicParsing/{exercisesId}")
    public Res<List<TopicVO>> allTopicParsing(@ApiParam(value = "章节练习id",required = true) @PathVariable Integer exercisesId){
        List<ReadChapterExercisesTopicPO> data = chapterExercisesTopicService
                .list(new QueryWrapper<ReadChapterExercisesTopicPO>().eq("chapter_exercises_id",exercisesId));
        List<Integer> topicIds = data.stream().map(ReadChapterExercisesTopicPO::getTopicId).collect(Collectors.toList());
        List<ReadTopicPO> topics = readTopicService.listByIds(topicIds);
        List<TopicVO> result = BeanCopierUtil.copy(topics, TopicVO.class);
        assert result != null;
        result.forEach(item -> {
            //item.setVideoUrl(FileUtil.getFileStr(item.getVideoUrl(),"kedu"));
            ReadChapterExercisesTopicPO commitTopic = chapterExercisesTopicService.getOne(new QueryWrapper<ReadChapterExercisesTopicPO>()
                    .eq("topic_id", item.getId())
                    .eq("chapter_exercises_id", exercisesId));
            item.setCommitAnswer(commitTopic.getCommitAnswer());
        });
        return Res.ok(result);
    }

    /**
     * 获取所有错题题目解析
     * @param exercisesId  练习id
     * @return 所有错题题目解析
     */
    @ApiOperation("获取获取当前章节练习id->所有错题题目解析")
    @GetMapping("/allWrongTopicParsing/{exercisesId}")
    public Res<List<TopicVO>> allWrongTopicParsing(@ApiParam(value = "章节练习id",required = true) @PathVariable Integer exercisesId){
        List<ReadChapterExercisesTopicPO> data = chapterExercisesTopicService
                .list(new QueryWrapper<ReadChapterExercisesTopicPO>()
                        .eq("chapter_exercises_id",exercisesId)
                        .eq("status",false));
        List<Integer> topicIds = data.stream()
                .map(ReadChapterExercisesTopicPO::getTopicId)
                .collect(Collectors.toList());
        if (topicIds.isEmpty()) return Res.ok(null);
        List<ReadTopicPO> topics = readTopicService.listByIds(topicIds);
        List<TopicVO> result = BeanCopierUtil.copy(topics, TopicVO.class);
        result.forEach(item -> {
            //item.setVideoUrl(FileUtil.getFileStr(item.getVideoUrl(),"kedu"));
            ReadChapterExercisesTopicPO commitTopic = chapterExercisesTopicService.getOne(new QueryWrapper<ReadChapterExercisesTopicPO>()
                    .eq("topic_id", item.getId())
                    .eq("chapter_exercises_id", exercisesId));
            item.setCommitAnswer(commitTopic.getCommitAnswer());
        });
        return Res.ok(result);
    }

    /**
     * 获取当前知识点练习题的排行榜
     * @param knowledgeId  知识点id
     * @param sortBy  排序方式
     * @return 返回当前知识点练习题的排行榜
     */
    @ApiOperation("获取当前知识点练习题的排行榜 knowledgeId-知识点id, sortBy-排序方式(error_num,correct_num,duration)")
    @GetMapping("/getTheLeaderBoard")
    public Res<HashMap<String,Object>> getTheLeaderBoard(
            @ApiParam(value = "知识点id",required = true) @RequestParam("knowledgeId") Integer knowledgeId,
            @ApiParam(value = "排序方式",required = true) @RequestParam("sortBy") String sortBy){
        QueryWrapper<ReadChapterExercisesPO> queryWrapper =
                new QueryWrapper<ReadChapterExercisesPO>().eq("knowledge_id", knowledgeId).isNotNull("end_time");
        if (sortBy.equals("correct_num")){
            queryWrapper.orderByDesc(sortBy);
        }
        if (sortBy.equals("error_num")){
            queryWrapper.orderByAsc(sortBy);
        }
        ChapterExercisesAndStudentVO self = new ChapterExercisesAndStudentVO();
        List<ReadChapterExercisesPO> data = chapterExercisesService.list(queryWrapper);
        List<ChapterExercisesAndStudentVO> exercisesVOs = BeanCopierUtil.copy(data, ChapterExercisesAndStudentVO.class);
        for (int i = 0; i < exercisesVOs.size(); i++) {
            ChapterExercisesAndStudentVO item = exercisesVOs.get(i);
            ViewUserPO userPO = viewUserService.getOne(new QueryWrapper<ViewUserPO>().eq("user_id", item.getStudentId()));
            if (item.getStudentId().equals(SecurityHelper.getCurrentUserId())){
                self.setDuration(DateUtil.getBetweenMinutes(item.getStartTime(),item.getEndTime()));
                self.setCorrectNum(item.getCorrectNum());
                self.setErrorNum(item.getErrorNum());
                self.setStartTime(item.getStartTime());
                self.setEndTime(item.getEndTime());
                self.setStudentId(item.getStudentId());
                self.setId(item.getId());
                self.setRanking(i+1);
                self.setHeadImgUrl(userPO.getHeadImgUrl());
                self.setStudentName(userPO.getNickName());
            }
            item.setStudentName(userPO.getNickName());
            item.setHeadImgUrl(userPO.getHeadImgUrl());
            item.setDuration(DateUtil.getBetweenMinutes(item.getStartTime(),item.getEndTime()));
        }
        HashMap<String,Object> result = new HashMap<>();
        result.put("self",self);
        if (sortBy.equals("duration")){//时间排序 由少到多
            List<ChapterExercisesAndStudentVO> collect = exercisesVOs.stream().sorted(
                    (e1,e2)->{
                        Long i1 = e1.getEndTime().getTime() - e1.getStartTime().getTime();
                        Long i2 = e2.getEndTime().getTime() - e2.getStartTime().getTime();
                        return i1.compareTo(i2);
                    }
            ).collect(Collectors.toList());
            result.put("all",collect);
        }else {
            result.put("all",exercisesVOs);
        }
        return Res.ok(result);
    }


    /**
     * 所有错题章节分类
     * @return 错题章节分类
     */
    @ApiOperation("根据当前所选科目获取错题章节分类")
    @GetMapping("/getAllWrongChapter/{subjectId}")
    public Res<List<ReadChapterPO>> getAllWrongChapter(@ApiParam(value = "科目id、subjectId") @PathVariable Integer subjectId){
        Integer currentUserId = SecurityHelper.getCurrentUserId();
        List<ReadChapterPO> data = chapterExercisesService.getAllWrongChapter(currentUserId,subjectId);
        return Res.ok(data);
    }

    /**
     * 所有错题章节分类
     * @return 错题章节分类
     */
    @ApiOperation("根据当前所选科目获取错题章节分类 包含知识点信息")
    @GetMapping("/getAllWrongChapterAndKnowledge/{subjectId}")
    public Res<List<ChapterAndKnowledgeVO>> getAllWrongChapterWrongQuestionSet(@ApiParam(value = "科目id、subjectId") @PathVariable Integer subjectId){
        Integer currentUserId = SecurityHelper.getCurrentUserId();
        List<ChapterAndKnowledgeVO> data =
                chapterExercisesService.getAllWrongChapterWrongQuestionSet(currentUserId,subjectId);
        return Res.ok(data);
    }




    /**
     * 获取所有错题知识点
     * @param chapterId 章节分类id
     * @return 获取所有错题知识点
     */
    @ApiOperation("根据当前所选章节 ---获取所有错题知识点")
    @GetMapping("/getAllWrongKnowledgePoint/{chapterId}")
    public Res getAllWrongKnowledgePoint(@ApiParam(value = "章节id、chapterId") @PathVariable Integer chapterId){
        Integer currentUserId = SecurityHelper.getCurrentUserId();
        List<ReadKnowledgePointPO> data = chapterExercisesService.getAllWrongKnowledgePoint(currentUserId,chapterId);
        return Res.ok(data);
    }


    /**
     * 获取所有错题知识点
     * @param KnowledgeId 知识点分类id
     * @return 获取所有错题知识点
     */
    @ApiOperation("根据当前所选知识点id 获取所以错题")
    @GetMapping("/getAllWrongTopic/{KnowledgeId}")
    public Res<List<TopicVO>> getAllWrongTopic(@ApiParam(value = "知识点id、KnowledgeId") @PathVariable Integer KnowledgeId){
        Integer currentUserId = SecurityHelper.getCurrentUserId();
        List<TopicVO> data = chapterExercisesService.getAllWrongTopic(currentUserId,KnowledgeId);
//        data.forEach(item->{
//            if (item != null)
//                item.setVideoUrl(FileUtil.getFileStr(item.getVideoUrl(),"kedu"));
//        });
        return Res.ok(data);
    }


}
